import React, {PureComponent} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {routerRedux, Link} from 'dva/router';
import {Icon, Menu, Switch, Dropdown, Form, Card, Select, List, Button} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import StandardFormRow from '../../components/StandardFormRow';


import styles from './ServiceList.less';

const {Option} = Select;
const FormItem = Form.Item;

/* eslint react/no-array-index-key: 0 */
@Form.create()
@connect(state => ({
    service: state.service,
}))
export default class ServiceList extends PureComponent {
    state = {
        pagination: {pageSize: 20, page: 1, total: 0},
        pid: '',
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'service/fetch',
            payload: {
                size: this.state.pagination.pageSize,
            },
        });
        this.props.dispatch({
            type: 'service/fetchCategories',
        });
    }

    onPageChange = (page, pageSize) => {
        console.log(page, pageSize);
        this.props.dispatch({
            type: 'service/fetch',
            payload: {
                size: this.state.pagination.pageSize,
                page,
                pid: this.state.pid,
            },
        });
    }
    handleFormSubmit = () => {
        const {form, dispatch} = this.props;
        // setTimeout 用于保证获取表单值是在所有表单字段更新完毕的时候
        setTimeout(() => {
            form.validateFields((err, values) => {
                if (!err) {
                    // eslint-disable-next-line
                    this.setState({
                        pid:values.pid
                    })
                    dispatch({
                        type: 'service/fetch',
                        payload: {
                            size: this.state.pagination.pageSize,
                            page:1,
                            pid: values.pid,
                        },
                    });
                }
            });
        }, 0);
    }
    onIndexShowChange = (checked, item) => {
        console.log(checked, item);
        const {form, dispatch} = this.props;
        dispatch({
            type: 'service/change',
            payload: {
                id: item.id,
                show_index: checked ? 1 : 0,
            },
            callback: () => {
                console.log('进入了回调');
                dispatch({
                    type: 'service/fetch',
                    payload: {
                        size: this.state.pagination.pageSize,
                        page: this.state.pagination.page,
                        pid: this.state.pid,
                    },
                });
            },
        });
    }
    componentDidCatch(error, errorInfo) {
        console.log(error,errorInfo)
    }
    handleAdd = () => {
        console.log('点击了行政');
        this.props.dispatch(routerRedux.push('/service/list/add'));
    }
    onMenuClick = (key, item) => {
        console.log(key);
        if (key === 'remove') {
            this.props.dispatch({
                type: 'service/remove',
                payload: {id: item.id},
                callback: () => {
                    this.props.dispatch.dispatch({
                        type: 'service/fetch',
                        payload: {
                            size: this.state.pagination.pageSize,
                            page: this.state.pagination.page,
                            pid: this.state.pid,
                        },
                    });
                },
            });
        } else if (key === 'edit') {
            this.props.dispatch(routerRedux.push(`/service/list/${item.id}`));
        }
    }

    render() {
        const {service: {data, loading, categories}, form} = this.props;
        const {getFieldDecorator} = form;
        const pagination = data.pagination;
        pagination.onChange = this.onPageChange;
        this.setState({
            pagination,
        });
        const menu = item => (
          <Menu onClick={({key}) => {
                this.onMenuClick(key, item);
            }}
          >
            <Menu.Item key="edit">
              <Icon type="form" /> 编辑
            </Menu.Item>
            <Menu.Item key="remove">
              <Icon type="delete" /> 删除
            </Menu.Item>
          </Menu>
        );
        const MoreBtn = item => (
          <Dropdown overlay={menu(item)}>
            <a>
                    更多操作 <Icon type="down" />
            </a>
          </Dropdown>
        );
        const cardList = data.list ? (
          <List

            pagination={pagination}
            loading={loading}
            grid={{gutter: 24, lg: 4, md: 3, sm: 2, xs: 1}}
            dataSource={data.list}
            renderItem={item => (
              <List.Item key={`service_card_${item.id}`}>
                <Card
                  className={styles.card}
                  hoverable
                  cover={<img style={{height: 140}} alt={item.name} src={item.thumb} />}
                >
                  <Card.Meta
                    title={<Link to={`/service/${item.id}`}>{item.name}</Link>}
                    description={item.description}
                  />
                    <div style={{marginTop: 10}}>
                        <span>服务ID</span>
                        <div >{item.id}
                        </div>
                    </div>
                  <div className={styles.price}>
                    <span>预估价格</span>
                    <div className={styles.money}><Icon
                      type="pay-circle"
                      style={{marginRight: 8}}
                    />{item.price}/{item.unit}
                    </div>
                  </div>
                  <div className={styles.price}>
                    <span>状态</span>
                    <div className={styles.money}>{item.status === 1 ? '启用' : '禁用'}</div>
                  </div>
                  <div className={styles.price}>
                    <span>首页显示</span>
                    <div><Switch
                      onChange={(checked) => {
                                    this.onIndexShowChange(checked, item);
                                }}
                      defaultChecked={item.show_index == 1}
                      checkedChildren="是"
                      unCheckedChildren="否"
                    />
                    </div>
                  </div>
                  <div className={styles.cardItemContent}>
                    <span>{moment(item.updated_at, 'YYYY-MM-DD HH:mm:ss').fromNow()}</span>
                    {MoreBtn(item)}
                  </div>
                </Card>
              </List.Item>
                )}
          />
        ) : null;

        return (
          <PageHeaderLayout
            title="服务列表"
          >
            <div className={styles.coverCardList}>
              <Card bordered={false}>
                <Form layout="inline">
                  <StandardFormRow title="所属类目" block style={{paddingBottom: 11}}>
                    <FormItem>
                      {getFieldDecorator('pid', {})(
                        <Select
                          allowClear
                          onChange={this.handleFormSubmit}
                          placeholder="全部分类"
                          style={{maxWidth: 200, width: '100%'}}
                        >
                          <Option value={0}>顶级分类</Option>
                          {categories.map((item, i) => (
                            <Option
                              key={`${item.id}-${i}-category`}
                              value={item.id}
                            >{item.name}
                            </Option>
                                            ))}
                        </Select>
                                    )}
                    </FormItem>
                  </StandardFormRow>
                </Form>
                <div className={styles.tableListOperator}>
                  <Button icon="plus" type="primary" onClick={this.handleAdd}>新增服务</Button>
                </div>
              </Card>
              <div className={styles.cardList}>
                {cardList}
              </div>
            </div>
          </PageHeaderLayout>
        );
    }
}
